import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:redux/redux.dart';
import 'package:lai_zhan/common/redux/AppState.dart';
import 'package:lai_zhan/common/style/AppStyle.dart';
import 'package:lai_zhan/common/dao/UserDao.dart';
import 'package:lai_zhan/common/model/userResult/user_result.dart';
import 'package:lai_zhan/widget/EnsureVisibleWhenFocused.dart';
import 'package:image_picker/image_picker.dart';
import 'package:lai_zhan/widget/BaseScaffold.dart';
import 'package:lai_zhan/widget/HeadPortrait.dart';
import 'package:lai_zhan/widget/RowRadio.dart';
import 'package:lai_zhan/widget/FlexOutLineButton.dart';
import 'package:lai_zhan/widget/EnsureVisibleTextInput.dart';
import 'package:lai_zhan/common/util/NavigatorUtil.dart';

class CompleteUserInfoPage extends StatefulWidget {
  static String rName = "complete";

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _CompleteUserInfoPageState();
  }
}

class _CompleteUserInfoPageState extends State<CompleteUserInfoPage> {
  UserResult userInfo;

  String _gender = "男";
  String _userImageUrl;
  bool hasInit = false;
  bool isUpdatePhoto = false; //判断是否上传图像
  String _uname;
  String _email;
  String _descr;
  File _photo;
  TextEditingController _uNameController = new TextEditingController();
  TextEditingController _emailController = new TextEditingController();
  TextEditingController _descrController = new TextEditingController();
  FocusNode _uNameFocusNode = new FocusNode();
  FocusNode _emailFocusNode = new FocusNode();
  FocusNode _descrFocusNode = new FocusNode();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    if (hasInit) return;
    hasInit = true;
    Store<AppState> store = StoreProvider.of(context);
    userInfo = store.state.userInfo;
  }

  @override
  Widget build(BuildContext context) {
    if (!isUpdatePhoto) {
      _userImageUrl =
          _gender == "男" ? 'lib/images/man.png' : 'lib/images/woman.png';
    }
    // TODO: implement build
    return new StoreBuilder(
        builder: (BuildContext context, Store<AppState> store) {
      return new BaseScaffold(
        title: '完善信息',
        back: () {
          Navigator.of(context).pop();
        },
        body: new Builder(builder: (BuildContext context) {
          return _renderBody(context);
        }),
      );
    });
  }

  Widget _renderBody(BuildContext context) {
    return new GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        FocusScope.of(context).requestFocus(new FocusNode());
      },
      child: new ListView(
        primary: false,
        children: <Widget>[
          new Center(
            child: new Container(
              margin: EdgeInsets.only(left: 20, right: 20, top: 40, bottom: 10),
              child: new Column(
                children: <Widget>[
                  new HeadPortrait(
                    imageTpye: ImageTpye.asset,
                    url: _userImageUrl,
                    onClick: () {
                      showImageBottomSheet(context);
                    },
                  ),
                  RowRadio(
                    radioNames: ['男', '女'],
                    onChange: setGender,
                  ),
                  _renderItem(
                      controller: _uNameController,
                      focusNode: _uNameFocusNode,
                      bigTitle: '您的昵称',
                      smallTitle: '让我们认识更好的您',
                      onChange: (value) {
                        _uname = value;
                      }),
                  _renderItem(
                      controller: _emailController,
                      focusNode: _emailFocusNode,
                      smallTitle: '您的邮箱',
                      onChange: (value) {
                        _email = value;
                      }),
                  _renderItem(
                      controller: _descrController,
                      focusNode: _descrFocusNode,
                      smallTitle: '您的介绍',
                      onChange: (value) {
                        _descr = value;
                      }),
                  new Container(
                    margin: EdgeInsets.only(left: 30,right: 30,top: 20,bottom: 40),
                    child: new FlexOutlineButton(text:'保存',
                      textColor: Color(AppColors.primaryColor),
                      borderColor: Color(AppColors.primaryColor),
                      onPress: (){
                        //提交用户信息
                        UserDao.updateUserInfo(gender: _gender,descr: _descr,email: _email,uname: _uname)
                            .then((res){
                              if(res.result){

                              }else{

                              }
                              NavigatorUtil.goBack(context);
                              NavigatorUtil.goIndex(context);
                            });
                      },
                    ),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  //显示底部弹窗
  showImageBottomSheet(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return new Padding(
            padding: EdgeInsets.all(5),
            child: new Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                new FlexOutlineButton(
                  text: '拍照',
                  textColor: Color(AppColors.primaryColor),
                  borderColor: Color(AppColors.primaryColor),
                  onPress: () {
                    getImage("Camera");
                  },
                ),
                new Padding(padding: EdgeInsets.all(5)),
                new FlexOutlineButton(
                  text: '从相册中选取',
                  textColor: Color(AppColors.primaryColor),
                  borderColor: Color(AppColors.primaryColor),
                  onPress: () {
                    getImage("Other");
                  },
                ),
              ],
            ),
          );
        });
  }

  //设置性别
  setGender(String gender) {
    setState(() {
      this._gender = gender;
    });
  }

  //获取图片
  getImage(String source) async {
    if (source == "Camera") {
      File photo = await ImagePicker.pickImage(source: ImageSource.camera);
      if (photo == null) return;
      setState(() {
        _userImageUrl = photo.path;
        isUpdatePhoto = true;
      });
    } else {
      File photo = await ImagePicker.pickImage(source: ImageSource.gallery);
      if (photo == null) return;
      setState(() {
        _userImageUrl = photo.path;
        isUpdatePhoto = true;
      });
    }
  }

  //保存
  void save() {
    UserDao.updateUserInfo(
            gender: _gender, descr: _descr, email: _email, uname: _uname)
        .then((res) {
      if (res.result) {
        //跳转到主页
      } else {
        //提示错误
      }
    });
  }

  _renderItem(
      {TextEditingController controller,
      FocusNode focusNode,
      String bigTitle,
      String smallTitle,
      ValueChanged<String> onChange}) {
    double fontSize;
    if (bigTitle != null) {
      fontSize = AppConstant.bigTextSize;
    } else {
      fontSize = AppConstant.bigTextSize;
    }

    return new Column(
      children: <Widget>[
        new Padding(padding: EdgeInsets.all(8)),
        bigTitle != null
            ? new Text(
                bigTitle,
                style: AppConstant.largeLargeText,
              )
            : new Container(),
        new Padding(padding: EdgeInsets.all(2)),
        smallTitle != null
            ? new Text(
                smallTitle,
                style: AppConstant.largeText,
              )
            : new Container(),
        new Padding(
          padding: EdgeInsets.only(left: 30, right: 30),
          child: new EnsureVisibleTextInput(
            focusNode: focusNode,
            controller: controller,
            fontSize: fontSize,
            textAlign: TextAlign.center,
            textColor: Colors.black,
            onChange: onChange,
          ),
        ),
      ],
    );
  }
}
